<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              placeholder="请输入内容"
              v-model="queryinfo.query"
              clearable
              @clear="getuserlists"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getuserlists"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="dialogVisible = true"
              >添加用户</el-button
            >
          </el-col>
        </el-row>
      </div>
      <el-table
        :data="userlists"
        stripe
        style="width: 100%; margin-top: 15px"
        border
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatechange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEdit(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deltetBtn(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
            >
              <!-- 分配角色按钮 -->
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="distribution(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top: 15px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryinfo.pagenum"
          :page-sizes="[2, 4, 6, 8]"
          :page-size="queryinfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totle"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部内容 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editShow"
      width="50%"
      @close="editClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editForm"
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary" @click="Edit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色弹框 -->
    <el-dialog
      title="角色分配"
      :visible.sync="userVisible"
      width="50%"
      @close="setRowDialog"
    >
      <div style="margin-bottom: 10px">
        <span>当前的用户：</span> <span>{{ userinfo.username }}</span>
      </div>
      <div style="margin-bottom: 20px">
        <span>当前的角色：</span> <span>{{ userinfo.role_name }}</span>
      </div>
      <div>
        <span>分配新角色：</span>
        <el-select v-model="selectid" placeholder="请选择">
          <el-option
            v-for="item in useoptions"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userVisible = false">取 消</el-button>
        <el-button type="primary" @click="distributionSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //验证手机号的规则
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(((13[0-9])|(14[5-7])|(15[0-9])|(17[0-9])|(18[0-9]))+\d{8})$/

      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      userlists: [],
      totle: 0,
      // 控制添加用户对话宽的显示和隐藏
      dialogVisible: false,
      // 控制编辑用户显示和隐藏
      editShow: false,
      // 分配角色弹框显示隐藏
      userVisible: false,
      // 添加用户的表单数据
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      //编辑表单数据
      editForm: {
        username: '',
        email: '',
        mobile: '',
      },
      //分配权限渲染对话框的数据
      userinfo: {},
      // 添加表单的验证规则对象
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur'],
          },
        ],
        mobile: [
          { required: true, message: '请输电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 所有角色列表
      useoptions: [],
      //已选择的id值
      selectid: '',
    }
  },
  created() {
    this.getuserlists()
  },
  methods: {
    async getuserlists() {
      const { data: res } = await this.$http.get(`users`, {
        params: this.queryinfo,
      })
      // console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败')
      this.userlists = res.data.users
      this.totle = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryinfo.pagesize = newSize
      this.getuserlists()
    },
    handleCurrentChange(newPage) {
      this.queryinfo.pagenum = newPage
      this.getuserlists()
    },
    async userStatechange(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('获取用户列表失败')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 监听添加用户对话框的关闭事件
    closed() {
      this.$refs.ruleForm.resetFields()
    },
    // 添加用户
    adduser() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        // 发起添加请求
        const { data: res } = await this.$http.post(`users`, this.ruleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户状态成功！')
        // 关闭对话框
        this.dialogVisible = false
        // 重新渲染
        this.getuserlists()
      })
    },
    // 展示编辑用户
    async showEdit(id) {
      // console.log(id)
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.editForm = res.data
      this.editShow = true
    },
    // 编辑用户
    Edit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        // 发起编辑请求
        const { data: res } = await this.$http.put(
          `users/` + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户失败')
        }
        this.$message.success('修改用户成功！')
        // 关闭对话框
        this.editShow = false
        // 重新渲染
        this.getuserlists()
      })
    },
    // 监听编辑用户对话框的关闭事件
    editClose() {
      this.$refs.ruleForm.resetFields()
    },
    // 删除用户
    async deltetBtn(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 如果用户确认删除则返回字符串confirm,取消则返回cancel
      // console.log(confirmResult)
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('用户删除失败')
        // 删除成功重新渲染
        this.$message.success('删除用户成功！')
        this.getuserlists()
      } else {
        this.$message.info('已取消删除')
      }
    },
    //分配角色
    async distribution(userinfo) {
      console.log(userinfo)
      //把所有数据赋给定义的userinfo
      this.userinfo = userinfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.useoptions = res.data
      this.userVisible = true
    },
    // 提交分配角色
    async distributionSure() {
      if (!this.selectid) return this.$message.error('亲选择要分配的角色')
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.selectid,
        }
      )
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配成功！！！')
      this.getuserlists()
      this.userVisible = false
    },
    // 分配角色对话框关闭事件
    setRowDialog() {
      // 清空上次的数据
      this.selectid = ''
      this.userinfo = ''
    },
  },
}
</script>

<style lang="less" scoped>
</style>